import Vue from 'vue'
import VueRouter from 'vue-router'
// 加载 login 文件夹，当里面有 index.vue 文件的时候默认加载，index 不需要完全指定
import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'
import store from '@/store'
import { Toast } from 'vant'

const Login = () => import('@/views/login')
const Search = () => import('@/views/search')
const List = () => import('@/views/search/list')
const ProDetail = () => import('@/views/prodetail')
const Order = () => import('@/views/order')
const Pay = () => import('@/views/pay')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/layout',
    component: Layout,
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  },
  {
    path: '/prodetail/:id',
    component: ProDetail
  },
  {
    path: '/order',
    component: Order
  },
  {
    path: '/pay',
    component: Pay
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/searchlist',
    component: List
  }
]
const router = new VueRouter({
  routes
})

// 全局前置导航守卫：
// 所有的路由在真正的被访问之前（解析渲染对应组件页面前），都会先经过全局前置守卫
// 只有全局前置守卫放行了，才会到达对应的页面
// to：到哪里去，到哪里去的完整路由信息对象（路径，参数）
// from：从哪里来，从哪里来的完整路由信息对象（路径，参数）
// next：是否放行：
//  1. next() 直接放行，放行到 to 要去的路径。
//  2. next(路径) 进行拦截，拦截到next里面配置的路径

// 定义一个数组，专门存放需要权限的页面
const authUrls = ['/pay', '/order']
router.beforeEach((to, from, next) => {
  // 访问页面时，访问或拦截的关键点是：用户是否有登录权限 token
  // 看 to.path 是否在 authUrls 中出现
  // console.log(to, from, next)
  if (!authUrls.includes(to.path)) {
    // 非权限页面，直接放行
    next()
    return
  }
  // 权限页面需要判断 token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    Toast.fail('请先登录')
    next('/login')
  }
})
export default router
